#include "dialogadd.h"
#include "ui_dialogadd.h"
#include <QButtonGroup>
#include <QMessageBox>
#include <QPushButton>
#include <QString>
#include "qthelper.h"
#include <QIntValidator>


DialogAdd::DialogAdd(stData* pData,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogAdd)
{
    m_Data = pData;
    ui->setupUi(this);
    this->initForm();
    this->initConfig();
}

DialogAdd::~DialogAdd()
{
    delete ui;
}

void DialogAdd::initForm()
{
    Qt::WindowFlags flags = this->windowFlags();
    flags &= ~Qt::WindowContextHelpButtonHint;
    this->setWindowFlags(flags);


    this->setWindowTitle("配置事件");

   // 创建一个按钮组
    QButtonGroup *radioGroup = new QButtonGroup(this);

    // 将单选按钮添加到按钮组中
    radioGroup->addButton(ui->radioButtonTurnOn);
    radioGroup->addButton(ui->radioButtonTurnOff);

    // 可以为每个按钮设置一个唯一的ID，方便后续获取选中按钮的信息
    //radioGroup->setId(ui->radioButtonTurnOn, true);
    //radioGroup->setId(ui->radioButtonTurnOff, false);

    QIntValidator *validatorWallId = new QIntValidator(1, 20, ui->lineEditWallID);
    ui->lineEditWallID->setValidator(validatorWallId);


    ui->lineEditName->setText(m_Data->strName);
    ui->lineEditWallID->setText(m_Data->strWallid);
    ui->textEditAddress->setText(m_Data->strAddress);

    if(m_Data->bTurnOn)
    {
        ui->radioButtonTurnOn->setChecked(true);
        ui->radioButtonTurnOff->setChecked(false);
    }
    else
    {
        ui->radioButtonTurnOn->setChecked(false);
        ui->radioButtonTurnOff->setChecked(true);
    }
}

void DialogAdd::initConfig()
{
    connect(ui->pushButtonSave, &QPushButton::clicked, this, &DialogAdd::onButtonSaveClicked);
    connect(ui->pushButtonClose, &QPushButton::clicked, this, &DialogAdd::reject);
}

void DialogAdd::onButtonSaveClicked()
{
    // 执行保存操作
    QString strName = ui->lineEditName->text();
    if (strName.isEmpty()) {
        //QMessageBox::warning(this, "提示", "请输入事件名称!");
        QtHelper::showMessageBoxError("请输入事件名称!");
        ui->lineEditName->setFocus();
        return;
    }

    QString strWallid = ui->lineEditWallID->text();
    if (strWallid.isEmpty()) {
        QtHelper::showMessageBoxError("请输入墙ID!");
        ui->lineEditWallID->setFocus();
        return;
    }

    QString strAddress = ui->textEditAddress->toPlainText();
    if (strAddress.isEmpty()) {
        QtHelper::showMessageBoxError("请输入墙地址!");
        ui->textEditAddress->setFocus();
        return;
    }

    // 定义一个正则表达式，匹配以逗号分隔的字符串
    QRegExp regExp("^([0-9]+,)*[0-9]+$");
    bool match1 = regExp.exactMatch(strAddress);
    if(!match1)
    {
        QMessageBox::warning(this, "提示", "请输入墙地址格式不正确,请检查!");
        ui->textEditAddress->setFocus();
        return;
    }

    m_Data->strName = strName;
    m_Data->strWallid = strWallid;
    m_Data->strAddress = strAddress;
    m_Data->bTurnOn = ui->radioButtonTurnOn->isChecked();

    // 关闭对话框
    accept();

    //return true;
}
